// pages/register/register.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    stepNum: 1,
    provinceList: [],
    cityList: [],
    areaList: [],
    info: {
      real_name: '',
      mobile: '',
      captcha: '',
      province_id: '',
      area_id: '',
      city_id: '',
      address_xx: '',
      password: '',
      confirm_password: '',
      id_card_image1: '',
      id_card_image2: '',
      health_certificate: '',
      qual_certificate: '',
      home_train_certificate: '',
      selected_ser_cat_ids: []
    },
    region: {
      selProvName: '请选择省份',
      selCityName: '请选择市',
      selAreaName: '请选择区',
    },
    servCats: {},
    catsItem: [],
    smsButton: false,
    smsText: '验证码',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initApp()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 
   */
  initApp: function(e) {
    let that = this,
        catsItem = [],
        data, k, j, i
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1s/provider/apply?access_token=' + accessToken,
        success: res => {
          data = res.data.data
          if(res.data.status === 1) {
            for(k in data.ser_cats) {
              for(j in data.ser_cats[k].child) {
                catsItem.push(data.ser_cats[k].child[j])
              }
            }
            that.getProv()
            if (data.info.province_id != '') {
              that.checkRegion(data.info.province_id,'prov')
            }
            if (data.info.city_id != '') {
              that.checkRegion(data.info.city_id, 'city')
            }
            if (data.info.area_id != '') {
              that.checkRegion(data.info.area_id, 'area')
            }
            that.setData({
              servCats: data.ser_cats,
              catsItem: catsItem,
              info: data.info
            })
          }
        }
      })
    })
  },

  checkRegion: function(id,str) {
    console.log(1)
    let that = this,
        data = that.data,
        k,j,i
    if(str == 'prov') {
      for(k in data.provinceList) {
        if (data.provinceList[k].id == id) {
          that.setData({
            'region.selProvName': data.provinceList[k].fullname
          })
        }
      }
    }

    if (str == 'city') {
      for (j in data.cityList) {
        if (data.cityList[j].id == id) {
          that.setData({
            'region.selCityName': data.cityList[j].fullname
          })
        }
      }
    }

    if (str == 'area') {
      for (i in data.areaList) {
        if (data.areaList[i].id == id) {
          that.setData({
            'region.selAreaName': data.areaList[i].fullname
          })
        }
      }
    }
  },

  /**
   * 
   */
  stepSubmit: function() {
    let that = this,
        num = that.data.stepNum,
        myApp = that.data.info
    if (num == 1) {
      if (myApp.real_name == '') {
        wx.showToast({
          icon: 'none',
          title: '请填写真实姓名',
        })

        return false
      }

      if (myApp.mobile == '') {
        wx.showToast({
          icon: 'none',
          title: '请填写手机号码',
        })

        return false
      }

      if (!(/^1[34578]\d{9}$/).test(myApp.mobile)) {
        wx.showToast({
          icon: 'none',
          title: '输入的手机号码有误',
        })

        return false
      }

      if (myApp.captcha == '') {
        wx.showToast({
          icon: 'none',
          title: '请输入验证码',
        })

        return false
      }

      if (that.data.region.selProvName == '请选择省份') {
        wx.showToast({
          icon: 'none',
          title: '请选择省份',
        })

        return false
      }

      if (that.data.region.selCityName == '请选择市') {
        wx.showToast({
          icon: 'none',
          title: '请选择市',
        })

        return false
      }

      if (that.data.region.selAreaName == '请选择区') {
        wx.showToast({
          icon: 'none',
          title: '请选择区',
        })

        return false
      }

      if (myApp.address_xx == '') {
        wx.showToast({
          icon: 'none',
          title: '请输入详细地址',
        })

        return false
      }

      if (myApp.password == '') {
        wx.showToast({
          icon: 'none',
          title: '请输入密码',
        })

        return false
      }

      if (myApp.password.length < 6) {
        wx.showToast({
          icon: 'none',
          title: '密码不能低于6位',
        })

        return false
      }

      if (myApp.confirm_password != myApp.password) {
        wx.showToast({
          icon: 'none',
          title: '两次密码输入需要一致',
        })

        return false
      }

    }

    if(num == 2) {
      if (myApp.id_card_image1 == '') {
        wx.showToast({
          icon: 'none',
          title: '请上传身份证正面',
        })

        return false
      }

      if (myApp.id_card_image2 == '') {
        wx.showToast({
          icon: 'none',
          title: '请上传身份证反面',
        })

        return false
      }
      
    }

    if (num == 3) {
      if (myApp.selected_ser_cat_ids.length == 0) {
        if (myApp.qual_certificate == '') {
          wx.showToast({
            icon: 'none',
            title: '请选择至少一项技能',
          })

          return false
        }
      }
    }

    that.reg(num)
    num++
    if (num <= 3){
      that.setData({
        stepNum: num
      })
    }
  },

  /**
   * 减法
   */
  stepMin: function() {
    let that = this,
      num = that.data.stepNum
    num--
    if (num >= 1) {
      that.setData({
        stepNum: num
      })
    }
  },

  reg: function(step) {
    let that = this,
        ids = that.data.info.selected_ser_cat_ids,
        myApp = that.data.info
    console.log(ids)
    if(step == 3) {
      that.setData({
        'info.selected_ser_cat_ids': ids.join()
      })
    } else {
      if(typeof ids === 'string') {
        that.setData({
          'info.selected_ser_cat_ids': ids.split(',')
        })
      }
    }
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1s/provider/apply?access_token=' + accessToken +'&step=' + step,
        method: 'POST',
        data: {
          info: JSON.stringify(that.data.info)
        },
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success: res => {
          wx.hideLoading()
          if(res.data.status === 1) {
            console.log(res)
            if(res.data.data.step === 3) {
              wx.showModal({
                showCancel: false,
                title: '提示',
                content: '信息提交成功',
                success: res => {
                  if(res.confirm) {
                    wx.switchTab({
                      url: '../user/user',
                    })
                  }
                }
              })
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.data.msg,
            })
          }
        }
      })
    })
  },

  /**
   * send message
   */
  sendSms: function() {
    let that = this,
        djs = 0
    if(that.data.info.mobile === '') {
      wx.showToast({
        icon: 'none',
        title: '手机号不能为空',
      })
      return false
    }
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1s/provider/send-sms-apply?access_token=' + accessToken,
        data: {
          mobile: that.data.info.mobile
        },
        success: res => {
          if(res.data.status === 1) {
            wx.showToast({
              icon: 'none',
              title: '发送验证码成功',
              success: res => {
                that.setData({
                  smsButton: true
                })
                djs = 60
                setInterval(function(){
                  if(djs == 0) {
                    that.setData({
                      smsButton: false,
                      smsText: '验证码'
                    })
                  } else {
                    that.setData({
                      smsText: djs
                    })
                    djs--
                  }
                },1000)
              }
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: res.data.msg,
            })
          }
        }
      })
    })
  },

  /**
   * getLocation
   */
  getProv: function() {
    let that = this
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1s/region/list?access_token=' + accessToken,
        data:{
          parent_id: 0
        },
        success: res => {
          that.setData({
            provinceList: res.data.data
          })
          wx.hideLoading()
        }
      })
    })
  },

  /**
   * 选择省份
   */
  changeProvince: function (e) {
    let that = this,
        i = e.detail.value,
        pid, name
    name = that.data.provinceList[i].fullname
    pid = that.data.provinceList[i].id
    that.setData({
      'info.province_id': pid,
      'region.selProvName': name
    })
    that.getCity(pid)
  },

  /**
   * 获取市
   */
  getCity: function (parentId) {
    let that = this
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1s/region/list?access_token=' + accessToken + '&parent_id=' + parentId,
        success: res => {
          that.setData({
            cityList: res.data.data
          })
          wx.hideLoading()
        }
      })
    })
  },

  /**
   * 市选择
   */
  changesCity: function (e) {
    let that = this,
        i = e.detail.value,
        pid, name
    name = that.data.cityList[i].fullname
    pid = that.data.cityList[i].id
    that.setData({
      'info.city_id': pid,
      'region.selCityName': name
    })
    that.getArea(pid)
  },

  getArea: function (parentId) {
    let that = this
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1s/region/list?access_token=' + accessToken + '&parent_id=' + parentId,
        success: res => {
          that.setData({
            areaList: res.data.data
          })
          wx.hideLoading()
        }
      })
    })
  },

  /**
  * 县区选择
  */
  changesArea: function (e) {
    let that = this,
        i = e.detail.value,
        pid,name
    name = that.data.areaList[i].fullname
    pid = that.data.areaList[i].id
    this.setData({
      'info.area_id': pid,
      'region.selAreaName': name
    });
  },

  /**
   * 上传方法
   * 
   * 1 身份证正面 2 身份证反面 3 健康证 4 从业资格证 5 家政培训
   * 
   */
  upLoad: function(e) {
    let that = this,
        bs = e.currentTarget.dataset.bs,
        data, tempFilePaths
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.chooseImage({
        success(res) {
          tempFilePaths = res.tempFilePaths
          wx.uploadFile({
            url: app.globalData.hostAPI + '/v1s/provider/upload?access_token=' + accessToken, // 仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            name: 'file',
            success(res) {
              data = JSON.parse(res.data)
              if(data.status === 1) {
                that.setData({
                  [bs]: data.data.url
                })
              } else {
                wx.showToast({
                  icon: 'none',
                  title: res.msg,
                })
              }
            }
          })
        }
      })
    })
  },

  /**
   * 选择技能
   */
  changeSkill: function(e) {
    let ids = e.detail.value
    this.setData({
      'info.selected_ser_cat_ids': ids
    })
  },


  /**
   * 记录input
   */

  nameValue: function (e) {
    this.setData({
      'info.real_name': e.detail.value
    })
  },

  telValue: function (e) {
    this.setData({
      'info.mobile': e.detail.value
    })
  },

  addValue: function(e) {
    this.setData({
      'info.address_xx': e.detail.value
    })
  },

  smsValue: function (e) {
    this.setData({
      'info.captcha': e.detail.value
    })
  },

  passValue: function (e) {
    this.setData({
      'info.password': e.detail.value
    })
  },

  rePassValue: function (e) {
    this.setData({
      'info.confirm_password': e.detail.value
    })
  }
})